package xnj.lazydog.btcontroller.MyViews;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import xnj.lazydog.btcontroller.ControlViews.Value;
import xnj.lazydog.btcontroller.R;

public class DataPackView extends View {

    public static final int DATA_TYPE_BOOL = 0;
    public static final int DATA_TYPE_BYTE = 1;
    public static final int DATA_TYPE_SHORT = 2;
    public static final int DATA_TYPE_INT = 3;
    public static final int DATA_TYPE_FLOAT = 4;


    public static final String[] DATA_TYPE_NAMES = new String[]{"BOOL","BYTE","SHORT","INT","FLOAT"};
    public static final String[] DATA_TYPE_INFO = new String[]{"逻辑值","字节值",
            "短整形","整形值","浮点数"};

    int type;

    float bar_ratio = 0.3f;
    float bmp_ratio = bar_ratio*0.7f;
    float w,h;
    public static Bitmap add,edit,delete;
    List<String> valueList;
    List<Value> values;

    float scrollX = 0;
    float scrolldX = 0;

    int color;
    int selectedIndex=0;
    String title;
    float [] scale = new float[]{0,0,0};
    float [] scale_set = new float[]{1,1,1};
    float [] scale_dot = new float[3];

    float bmp_unit_ratio = 2f;
    float bmp_size,bar_height;

    float value_item_ratio = 2.5f;
    float value_circle_ratio = 0.45f;

    RectF color_rect = new RectF(0,0,0,0);
    boolean isDrawing = true;
    Paint p;
    InputMethodManager inputMethodManager;

    public DataPackView(Context context,AttributeSet attrs) {
        super(context, attrs);
        inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        p = new Paint();
        p.setFlags(Paint.FILTER_BITMAP_FLAG);
        p.setAntiAlias(true);

        valueList = new ArrayList<>();
    }

    public void  initDataPackView(int color, int type, List<String> valueList, List<Value> values, DataViewListener listener)
    {
        this.color = color;
        this.type = type;
        this.values = values;
        this.title = DATA_TYPE_INFO[type];
        this.valueList = valueList;
        this.listener = listener;
    }



    void start()
    {
        if(!isDrawing) {
            isDrawing = true;
            postInvalidate();
        }
    }

    void stop()
    {
        isDrawing = false;
    }

    float value_item_px;
    float value_item_size;

    float scale_err_sum;

    float value_circle_center_y;
    float value_number_bot_y;
    float value_text_bot_y;
    float value_number_text_size;
    float value_text_text_size;
    float value_circle_radius;
    float value_item_x;
    @Override
    protected void onDraw(Canvas canvas) {
        w = getWidth();
        h = getHeight();

        bmp_size = h*bmp_ratio;
        bar_height = h*bar_ratio;

        value_item_size = (h-bar_height)*value_circle_ratio;
        value_item_px = value_item_size*value_item_ratio;


        if (add == null) {
            add = IDBitmap.getBitmapScaled(getResources(), R.drawable.add_data,bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
            edit = IDBitmap.getBitmapScaled(getResources(), R.drawable.edit_name_button,bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
            delete = IDBitmap.getBitmapScaled(getResources(), R.drawable.delete,bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
        }

        scale_err_sum = 0;
        for(int i=0;i<scale.length;i++)
        {
            scale_dot[i] = scale_set[i]-scale[i];
            scale_err_sum+=Math.abs(scale_dot[i]);

            if(scale_dot[i]<0)
                scale[i]+=scale_dot[i]*0.1f;
            else
                scale[i]+=scale_dot[i]*0.3f;

        }


        if(scale_err_sum<0.001f) {
            stop();
            for(int i=0;i<scale.length;i++)
            {
                scale[i]=scale_set[i];
            }
        }


        if(!isDragging)
        scrollX += scrolldX*0.433f;

        if(Math.abs(scrolldX)>15)
            scrolldX*=0.97f;
        else
            scrolldX*=0.8f;


        if(Math.abs(scrolldX)>0.001f)
            isDrawing = true;

//        if(scrollX>0) {
//            scrolldX -= scrollX * 0.1f;
//            scrolldX *=0.75f;
//        }


        if(scrollX<-valueList.size()*value_item_px+w)
        {
            scrollX=-valueList.size()*value_item_px+w;
        }

        if(scrollX>0)
            scrollX = 0;


        p.setARGB(255,233,233,233);
        canvas.drawRect(0,0,w,h*bar_ratio,p);
        color_rect.left = bmp_size*0.5f;
        color_rect.right = bmp_size*1.5f;
        color_rect.top = (bar_height-bmp_size)*0.5f;
        color_rect.bottom= (bar_height+bmp_size)*0.5f;
        p.setColor(color);
        canvas.drawRoundRect(color_rect,bmp_size*0.2f,bmp_size*0.2f,p);
        p.setTextSize(bmp_size*0.7f);
        p.setARGB(255,44,44,44);
        if(title==null)
            title = "null" ;


        p.setTextAlign(Paint.Align.LEFT);
        canvas.drawText(title,bmp_size*2,color_rect.bottom-bmp_size*0.25f,p);

        p.setTextAlign(Paint.Align.RIGHT);
        p.setColor(0xff333333);
        canvas.drawText(valueList.size()+"*"+DATA_TYPE_NAMES[type].toLowerCase(),w-bmp_size*(bmp_unit_ratio*3f),color_rect.bottom-bmp_size*0.25f,p);
        //canvas.drawARGB(255,0,0,0);

        canvas.save();
        canvas.translate(w-bmp_size*(bmp_unit_ratio*2.5f),bar_height*0.5f);
        canvas.scale(scale[0],scale[0]);
        canvas.drawBitmap(add,-bmp_size*0.5f,-bmp_size*0.5f,p);
        canvas.restore();


        canvas.save();
        canvas.translate(w-bmp_size*(bmp_unit_ratio*1.5f),bar_height*0.5f);
        canvas.scale(scale[1],scale[1]);
        canvas.drawBitmap(edit,-bmp_size*0.5f,-bmp_size*0.5f,p);
        canvas.restore();

        canvas.save();
        canvas.translate(w-bmp_size*(bmp_unit_ratio*0.5f),bar_height*0.5f);
        canvas.scale(scale[2]*0.8f,scale[2]*0.8f);
        canvas.drawBitmap(delete,-bmp_size*0.5f,-bmp_size*0.5f,p);
        canvas.restore();

        p.setTextAlign(Paint.Align.CENTER);
        //p.setTextSize(value_item_size*0.4f);

        value_circle_center_y = (bar_height+(h-bar_height)*0.4f);
        value_number_bot_y = (bar_height+(h-bar_height)*0.4f)+value_item_size*0.177f;
        value_text_bot_y = (bar_height+(h-bar_height)*0.7f)+value_item_size*0.4f;

        value_circle_radius = value_item_size*0.5f;
        value_number_text_size = value_item_size*0.45f;
        value_text_text_size = value_item_size*0.4f;


        for(int i=0;i<valueList.size();i++)
        {
            value_item_x = scrollX+(i+0.5f)*value_item_px;

            canvas.save();
            canvas.clipRect(scrollX+i*value_item_px,0,scrollX+(i+1)*value_item_px,h);
            if(selectedIndex==i)
                p.setARGB(255,255,255,255);
            else
                p.setARGB(255,100,100,100);

            canvas.drawCircle(value_item_x,value_circle_center_y,value_circle_radius,p);

            if(selectedIndex==i)
                p.setARGB(255,22,22,22);
            else
                p.setARGB(255,255,255,255);

            p.setTextSize(value_number_text_size);
            canvas.drawText(""+i,value_item_x,value_number_bot_y,p);
            p.setTextSize(value_text_text_size);
            p.setARGB(255,55,55,55);
            canvas.drawText(valueList.get(i),value_item_x,value_text_bot_y,p);
            canvas.restore();
        }

        if(isDrawing)
            invalidate();
    }

    boolean isDragging = false;

    float px,py;
    float fx,fy;

    float fScrollX =0;
    float lScrollX;

    int tIndex;
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        px = event.getX();
        py = event.getY();

        if(event.getAction()==MotionEvent.ACTION_DOWN) {
            start();
            isDragging = false;
            if(py<bar_height) {
                if(px>w-bmp_size*bmp_unit_ratio) {
                    scale_set[2] = 1.4f;
                }else if(px>w-bmp_size*bmp_unit_ratio*2)
                    scale_set[1] = 1.4f;
                else if(px>w-bmp_size*bmp_unit_ratio*3)
                    scale_set[0] = 1.4f;

            }else {
                //select(0);
            }
            fx = px;
            fy = py;

            fScrollX = scrollX;
            lScrollX = scrollX;
        }
        if(event.getAction()==MotionEvent.ACTION_MOVE) {

            start();
            if((px-fx)*(px-fx)+(py-fy)*(py-fy)>400)
                isDragging = true;

            scrollX = fScrollX+(px-fx);

            scrolldX +=(scrollX-lScrollX-scrolldX)*0.2f;

            lScrollX = scrollX;
        }

        if(event.getAction()==MotionEvent.ACTION_UP) {
            start();
            if(!isDragging)
            {
                if(py<bar_height) {

                    if(px>w-bmp_size*bmp_unit_ratio) {
                        delete();
                    }else if(px>w-bmp_size*bmp_unit_ratio*2)
                        edit();
                    else if(px>w-bmp_size*bmp_unit_ratio*3)
                         add();

                }else {

                    tIndex = (int)((px-scrollX)/value_item_px);
                    if(tIndex>=0&&tIndex<valueList.size()) {
                        selectedIndex = tIndex;

                    }

                }
            }

            for (int i = 0; i < scale.length; i++)
                scale_set[i] = 1f;

            isDragging = false;
        }

        return true ;
    }

    private static final String TAG = "DataPackView";

    void add()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View v = LayoutInflater.from(getContext()).inflate(R.layout.data_pack_new_data,null);
        builder.setView(v);
        final AlertDialog dialog = builder.create();
        if(dialog.getWindow()!=null)
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        TextView title = v.findViewById(R.id.new_value_type_title);
        final EditText name = v.findViewById(R.id.new_value_name);
        ImageView imageView = v.findViewById(R.id.new_value_logo);
        imageView.setImageResource(R.drawable.add_data);
        Button confirm = v.findViewById(R.id.new_value_confirm);
        Button cancel = v.findViewById(R.id.new_value_cancel);
        String s = "添加一个"+DATA_TYPE_NAMES[type]+"变量";
        title.setText(s);
        s = DATA_TYPE_NAMES[type] + valueList.size();
        name.setText(s);
        name.setSelection(0,s.length());

        confirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                valueList.add(name.getText().toString());

                values.add(new Value(type));

                selectedIndex = valueList.size()-1;
                scroll(selectedIndex);
                dialog.dismiss();
                start();
                if(listener!=null)
                    listener.onAddNewData(type,selectedIndex,valueList.get(selectedIndex));
            }
        });
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                start();
            }
        });
        dialog.show();


        postDelayed(new Runnable() {
            @Override
            public void run() {
                inputMethodManager.showSoftInput(name,InputMethodManager.SHOW_IMPLICIT);
            }
        },400);

    }





    void edit()
    {
        if(selectedIndex<0||selectedIndex>=valueList.size())
            selectedIndex = 0;
        else {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            View v = LayoutInflater.from(getContext()).inflate(R.layout.data_pack_new_data, null);
            builder.setView(v);
            final AlertDialog dialog = builder.create();
            if(dialog!=null&&dialog.getWindow()!=null)
              dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            ImageView imageView = v.findViewById(R.id.new_value_logo);
            imageView.setImageResource(R.drawable.edit_name_button);
            TextView title = v.findViewById(R.id.new_value_type_title);
            final EditText name = v.findViewById(R.id.new_value_name);
            Button confirm = v.findViewById(R.id.new_value_confirm);
            Button cancel = v.findViewById(R.id.new_value_cancel);
            String s = "修改变量名称";
            title.setText(s);
            name.setText(valueList.get(selectedIndex));

            //name.setSelection(0);

            name.setSelection(0,valueList.get(selectedIndex).length());


            confirm.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    valueList.set(selectedIndex, name.getText().toString());
                    //scroll(selectedIndex);
                    dialog.dismiss();
                    if(listener!=null)
                        listener.onEditDataName(type,selectedIndex,valueList.get(selectedIndex));
                    start();
                }
            });
            cancel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    start();
                }
            });
            dialog.show();

            postDelayed(new Runnable() {
                @Override
                public void run() {
                    inputMethodManager.showSoftInput(name,InputMethodManager.SHOW_IMPLICIT);
                }
            },400);

        }
    }

    void delete()
    {
        if(selectedIndex>=valueList.size()||selectedIndex<0)
            selectedIndex = 0;
        else {

            values.remove(selectedIndex);
            valueList.remove(selectedIndex);
            if(listener!=null)
                listener.onDeleteData(type,selectedIndex);
            scroll(selectedIndex);
            if (selectedIndex >= valueList.size())
                selectedIndex = valueList.size() - 1;
        }
    }

    void scroll(int i)
    {
        if(i>=0&&i<valueList.size())
        {
            scrollX = w*0.5f-value_item_px*(i+0.5f);
        }
    }

    DataViewListener listener;

    public interface  DataViewListener{

        void onAddNewData(int type,int index,String name);
        void onDeleteData(int type,int index);
        void onEditDataName(int type,int index,String name);

    }


}
